﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

using Gurucore.Framework.Core;
using Gurucore.Framework.Core.Proxy;

namespace Gurucore.Framework.DataAccess.Persistence
{
	public class DTOProxier
	{
		public DTOProxier()
		{
		}

		public Type GetProxyClass<T>()
		{
			Type oDTOType = typeof(T);
			return GetProxyClass(oDTOType);
		}

		public Type GetProxyClass(Type p_oDTOType)
		{
			TableInfoManager oTableInfoMgr = Application.GetInstance().GetGlobalSharedObject<TableInfoManager>();
			TableInfo oTableInfo = oTableInfoMgr.GetTableInfo(p_oDTOType);

			ProxyGenerator oGenerator = new ProxyGenerator(p_oDTOType);

			if (!oGenerator.IsGenerated())
			{
				TextReader oReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Gurucore.Framework.DataAccess.Persistence.DTOProxyTemplate.tpl"));
				string sTemplate = oReader.ReadToEnd();
				oReader.Close();
				oGenerator.SetTemplate(sTemplate);

				foreach (string sColumn in oTableInfo.Column)
				{
					oGenerator.AddGetterInterceptor(oTableInfo.Property[sColumn], string.Empty, string.Empty, InterceptorType.CallWrapper);
				}
			}
			return oGenerator.GetProxyClass();
		}
	}
}
